<template>
	<view class="detail-con" :style="{ minHeight: heightVal + 'px' }">
		<custom-nav-bar title="摄像头详情" :navHeight="statusHeight" />
		<u-toast ref="uToast"></u-toast>
		<view class="videoBox">
			<flv-player v-if="videoUrl" :streamUrl="videoUrl" ref="childRef"></flv-player>
			<!-- #ifdef APP-PLUS -->
			<view class="inner" ref="player" :src="videoUrl"></view>
			<!-- #endif -->
		</view>
		<RemoteControl v-show="showRemote" @touchStart="handleTouchStart" @touchEnd="handleTouchEnd" @getResUrl="getResUrlFn"></RemoteControl>
		<view class="btncon">
			<u-button type="primary" :plain="true" class="w6em" @click="handleRemoteShow">{{ showRemote ? '隐藏云台' : '显示云台' }}</u-button>
			<u-button class="w6em" @click="handleTurns" type="primary" :plain="true" text="刷新"></u-button>
		</view>
		<view class="tips" v-if="showRemote" style="width: 690rpx; margin: 0rpx auto; margin-top: 60rpx; font-size: 28rpx; color: #aaa; text-align: center; line-height: 40rpx">
			提示：长按“语音按钮”发送语音，长按方向键调整摄像头，设备操作有延迟，请耐心调整。
		</view>
		<template v-if="!showRemote">
			<view id="the-id" style="height: 20rpx; margin-top: 2rpx"></view>
			<view class="itemBox itemBoxFirst">
				<view style="width: 160rpx; white-space: nowrap">施工计划：</view>
				<u-input @confirm="handleSearch" confirm-type="search" placeholder="请输入施工计划" v-model="inputWorkName" />
				<u-button class="mlr10" type="primary" @click="handleSearch">查询</u-button>
			</view>
			<view class="itemBox">
				<view style="width: 160rpx; white-space: nowrap">车牌号码：</view>
				<u-input placeholder="请输入车牌号" v-model="carNo" />
				<!-- <u-button type="primary" class="mlr10" @click="handleCarNo">确认</u-button> -->
			</view>
			<view class="itemBox">
				<view style="width: 160rpx; white-space: nowrap">是否全天：</view>
				<u-switch class="switchBox" v-model="isAllDay" @change="switchChange" activeColor="#3c9cff"></u-switch>
			</view>
			<u-button type="primary" class="bottomBtn" @click="handleCarNo">确认</u-button>

			<!-- 搜索结果 -->
			<view class="searchData" v-if="dataList.length">
				<view class="resTitle">查询结果：</view>
				<view class="itemsbox2">
					<view class="itembox" v-for="(item, index) in dataList" :key="index" @click="clickTarget(item, index)" :class="{ active: activeIndex === index }">
						<view class="itemboxleft">
							<view class="tempBox">
								<view class="innerTxt">{{ item.buildname }}</view>
								<view class="smallTxt">负责人：{{ item.reviewemployeeid }}</view>
							</view>
						</view>
						<view class="itemboxright" v-if="activeIndex == index">
							<view class="btn" @click="confirmSelect(item, index)">确认选择</view>
						</view>
					</view>
				</view>
			</view>
		</template>
	</view>
</template>

<script>
import RemoteControl from '@/components/RemoteControl/RemoteControl.vue';
import { getAllBuildPlan, buildPlanFeedBack, getUrlByDeviceIdAW, buildPlanconcat, cameraControl, sendVoice } from '../../../api/device/index.js';
import FlvPlayer from '@/components/FlvPlayer.vue';

export default {
	components: {
		RemoteControl,
		FlvPlayer
	},
	data() {
		return {
			videoUrl: '',
			inputWorkName: undefined,
			inputWorkId: undefined,
			carNo: '', // 车牌号
			showRemote: false, // 遥控器展示状态
			heightVal: undefined,
			dataList: [],
			isAllDay: false, //开关

			//选择查询结果
			activeIndex: 0,
			// 摄像头id
			cameraId: undefined,
			statusHeight: 0
		};
	},
	onLoad(option) {
		// console.log(option);
		this.cameraId = option.id;
		this.heightVal = uni.getSystemInfoSync().windowHeight;
	},
	onShow() {
		this.statusHeight = uni.getStorageSync('systemHeight');
	},
	onReady() {
		this.videoContext = uni.createVideoContext('myVideo');
		this.$nextTick(() => {
			const animation = uni.createAnimation({
				duration: 1000,
				timingFunction: 'ease'
			});
			animation.rotateY(180).step();
			this.animationData = animation.export();
		});
	},
	onReachBottom() {
		console.log(111);
	},
	mounted() {
		this.playVedio();
	},
	beforeDestroy() {
		// #ifdef APP-PLUS
		this.player.close();
		// #endif
	},
	methods: {
		getResUrlFn(url) {
			console.log(url);
			let obj = {
				deviceId: uni.getStorageSync('userInfo').cn1,
				audioData: url
			};
			console.log(obj);
			sendVoice(obj)
				.then((res) => {
					console.log('上传音频', res);
				})
				.catch((err) => {
					console.log('上传音频失败', err);
				});
		},
		//播放视频
		playVedio() {
			let obj = {
				deviceType: '2',
				checkPhone: uni.getStorageSync('userInfo').phone,
				userid: uni.getStorageSync('userInfo').userid,
				deviceid: uni.getStorageSync('userInfo').cn1
			};
			this.videoUrl = '';
			// console.log('请求参数', obj);
			getUrlByDeviceIdAW(obj)
				.then((res) => {
					console.log(888, res);
					if (res.code == 500) {
						uni.showToast({
							icon: 'none',
							title: res.msg,
							duration: 2500
						});
					}
					if (res.data) {
						uni.showToast({
							icon: 'none',
							title: res.msg,
							duration: 2500
						});
						this.videoUrl = res.data;

						// #ifdef APP-PLUS
						console.log('当前是APP环境');
						this.startPlay();
						// #endif
					}
				})
				.catch((err) => {
					console.log(err);
					uni.showToast({
						icon: 'none',
						title: err.msg
					});
				});
		},

		//搜索
		handleSearch() {
			let obj = {
				phone: uni.getStorageSync('userInfo').phone,
				buildname: this.inputWorkName
			};
			console.log('校验参数', obj);
			getAllBuildPlan(obj).then((res) => {
				console.log(999, res);
				this.dataList = res.data;

				uni.showToast({
					icon: 'none',
					title: '查询成功'
				});

				if (res.data.length) {
					this.listShow = true;
					//如果请求数据不为空，向下滚动页面
					setTimeout(() => {
						uni.pageScrollTo({
							selector: '#the-id',
							duration: 150
						});
					}, 50);
				} else {
					uni.showToast({
						icon: 'none',
						title: '无可查看施工计划'
					});
				}
			});
		},

		//车牌号上传
		carNumUpload() {
			let obj = {
				phone: uni.getStorageSync('userInfo').phone,
				planid: this.inputWorkId,
				numberplate: this.carNo
			};
			buildPlanFeedBack(obj).then((res) => {
				// console.log(777, res);
				uni.showToast({
					icon: 'none',
					title: res.msg
				});
			});
		},

		//绑定施工计划
		addBuildPlan() {
			let obj = {
				buildid: this.inputWorkId + '',
				userid: uni.getStorageSync('userInfo').userid,
				buildname: this.inputWorkName,
				time_slot: this.isAllDay ? '全天' : ''
			};
			console.log(obj);
			buildPlanconcat(obj).then((res) => {
				console.log(555, res);
				uni.showToast({
					icon: 'none',
					title: res.msg
				});
			});
		},

		//播放视频
		startPlay() {
			this.player = plus.video.createVideoPlayer('player', {
				src: this.videoUrl,
				top: '0',
				width: '100%',
				height: '300px',
				autoplay: true
			});

			const webview = this.$scope.$getAppWebview();
			webview.append(this.player);

			//不同机型设置高度
			this.$nextTick(() => {
				const element = this.$refs.player;
			});
		},

		//刷新
		handleTurns() {
			this.playVedio();
		},

		//显示云台
		handleRemoteShow() {
			this.showRemote = !this.showRemote;
		},
		//开关-是否全天
		switchChange(e) {
			console.log(e);
		},
		//播放器加载
		videoErrorCallback() {
			console.log('videoErrorCallback');
		},

		//长按遥控
		handleTouchStart(direction) {
			console.log('长按开始', direction);
			let obj = {
				userid: uni.getStorageSync('userInfo').userid,
				checkPhone: uni.getStorageSync('userInfo').phone,
				deviceType: '摄像头',
				deviceid: uni.getStorageSync('userInfo').cn1,
				operator: '',
				speed: 255
			};
			if (direction == 'up') {
				obj.operator = 1;
			} else if (direction == 'down') {
				obj.operator = 2;
			} else if (direction == 'left') {
				obj.operator = 3;
			} else if (direction == 'right') {
				obj.operator = 4;
			}
			this.cameraControlFn(obj);
		},
		//长按结束
		handleTouchEnd(e) {
			console.log('长按结束', e);
			let obj = {
				userid: uni.getStorageSync('userInfo').userid,
				checkPhone: uni.getStorageSync('userInfo').phone,
				deviceType: '摄像头',
				deviceid: uni.getStorageSync('userInfo').cn1,
				operator: 0,
				speed: 255
			};
			this.cameraControlFn(obj);
		},
		//发起遥控请求
		cameraControlFn(obj) {
			cameraControl(obj)
				.then((res) => {
					console.log(258456, res);
					if (res.json.msg == '失败') {
						uni.showToast({
							title: '已达本侧最大转动幅度',
							icon: 'none',
							duration: 3000
						});
					}
				})
				.catch((err) => {
					uni.showToast({
						icon: 'none',
						title: err.msg,
						duration: 2600
					});
				});
		},
		//用户点击搜索结果某一项
		setDataOne(e) {
			console.log(e);
		},
		clickTarget(target, index) {
			// console.log(target);
			this.activeIndex = index;
		},
		//确认选择
		confirmSelect(item) {
			this.inputWorkName = item.buildname;
			this.inputWorkId = item.id;

			uni.pageScrollTo({
				scrollTop: 0,
				duration: 150
			});
		},
		//用户确认提交
		handleCarNo() {
			//查看有没有施工计划
			if (!this.inputWorkName || !this.inputWorkId) {
				uni.showToast({
					title: '请填写施工计划搜索后选择施工计划',
					duration: 2000,
					icon: 'none'
				});
				return;
			}

			//车牌号校验开始
			if (this.carNo.replace(/[\s-]/g, '') == '') {
				uni.showToast({
					title: '请输入车牌号',
					duration: 2000,
					icon: 'none'
				});
				return;
			}
			if (!this.validateLicensePlate(this.carNo)) {
				uni.showToast({
					title: '车牌号输入有误',
					duration: 2000,
					icon: 'none'
				});
				return;
			}
			//车牌号校验通过  施工计划已选
			this.carNumUpload();
			this.addBuildPlan();
		},
		//车牌号校验
		validateLicensePlate(plateNumber) {
			// 去除所有空格和特殊字符
			const plate = plateNumber.replace(/[\s-]/g, '').toUpperCase();

			// 定义车牌号正则表达式
			const patterns = [
				// 普通汽车（新能源+传统）
				/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/,
				// 新能源车牌
				/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z](?:[0-9]{5}[A-HJ-NP-Z0-9]|[A-HJ-NP-Z0-9][0-9]{4}[A-HJ-NP-Z0-9])$/,
				// 特种车牌（如军牌、武警牌等）
				/^[A-Z]{2}[0-9]{5}$/,
				/^WJ[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{0,1}[0-9]{4}[A-Z0-9]$/,
				/^[A-Z]{1}[0-9]{5}$/,
				/^[A-Z]{1}[D][0-9]{3}[0-9A-Z]$/
			];

			// 检查是否符合任一模式
			return patterns.some((pattern) => pattern.test(plate));
		}
	}
};
</script>

<style lang="scss" scoped>
.bottomBtn {
	width: 690rpx;
	margin: 21rpx auto;
}
.u-button {
	border-radius: 12rpx !important;
}

.u-input {
	border-radius: 12rpx !important;
	width: 300rpx;
	height: 42rpx !important;
}
.paddingBox {
	height: 120rpx;
	width: 100%;
}

.searchData {
	width: 690rpx;
	min-height: 300rpx;
	margin: 35rpx auto;
	border-top: 1rpx solid #ddd;
	// background-color: skyblue;
	padding-bottom: 300rpx;

	.itemsbox2 {
		width: 690rpx;
		// background-color: pink;
		box-sizing: border-box;
		padding-bottom: 90rpx;
		position: relative;
		z-index: 6;

		.itembox {
			min-height: 144rpx;
			width: 690rpx;
			border: 1rpx solid #e0e0e0;
			box-sizing: border-box;
			border-radius: 12rpx;
			background-color: #fff;
			padding: 24rpx;
			display: flex;
			justify-content: space-between;
			margin-bottom: 20rpx;

			.itemboxleft {
				width: 500rpx;
				display: flex;
				// background-color: yellow;

				.itemImg {
					display: block;
					width: 96rpx;
					height: 96rpx;
					margin: auto 0;
					margin-right: 16rpx;
					border-radius: 14rpx;
				}

				.tempBox {
					width: 460rpx;
					// background-color: skyblue;

					.innerTxt {
						font-size: 34rpx;
						color: #222222;
						font-weight: 800;
					}

					.smallTxt {
						font-size: 26rpx;
						color: rgba(34, 34, 34, 0.6);
						// white-space: nowrap;
						// overflow: hidden;
						// text-overflow: ellipsis;
						margin-top: 16rpx;
					}
				}
			}

			.itemboxright {
				min-height: 96rpx;
				width: 146rpx;
				display: flex;
				align-items: center;
				box-sizing: border-box;
				// background-color: pink;

				.btn {
					// background-color: #222222;
					background-color: #3c9cff;
					width: 146rpx;
					height: 70rpx;
					line-height: 70rpx;
					color: #fff;
					font-size: 26rpx;
					text-align: center;
					border-radius: 12rpx;
				}
			}
		}

		.active {
			border: 1rpx solid #7de0ff;
			box-sizing: border-box;
			background-color: rgba(247, 251, 255, 1);
		}
	}

	.resTitle {
		padding-top: 20rpx;
		font-size: 34rpx;
		font-weight: bold;
		color: #3c9cff;
		margin-bottom: 20rpx;
		margin-top: 30rpx;
	}

	.tableHead {
		width: 100%;
		height: 84rpx;
		line-height: 84rpx;
		background-color: #ddd;
		border-radius: 12rpx;
		display: flex;
		justify-content: space-between;
		color: rgba(0, 0, 0, 0.85);

		.left {
			width: 530rpx;
			height: 100%;
			text-align: center;
		}

		.right {
			width: 140rpx;
			text-align: center;
		}
	}

	.resItem {
		width: 100%;
		min-height: 40rpx;
		margin: 10rpx 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15rpx 0;
		padding-bottom: 25rpx;
		border-bottom: 1rpx solid #ddd;
		color: rgba(0, 0, 0, 0.65);

		.leftThings {
			width: 530rpx;
			height: 100%;
			text-align: center;
		}

		.rightThings {
			width: 140rpx;
			text-align: center;
		}
	}
}
.itemBox {
	display: flex;
	width: 690rpx;
	height: 70rpx;
	line-height: 70rpx;
	margin: 0 auto;
	margin-top: 20rpx;
	// background-color: skyblue;
	display: flex;
	align-items: center;

	.switchBox {
		width: 100%;
		height: 100%;
	}

	::v-deep .uni-input-input,
	.uni-input-placeholder {
		width: 350rpx !important;
	}
}

.itemBoxFirst {
	margin-top: 0rpx;
}

::v-deep .remote-control {
	margin: 50rpx 0 !important;
}

.detail-con {
	background: #f4f4f4;
	perspective: 1000;

	.videoBox {
		height: 300px;
		width: 100%;
		display: block;
		// background-image: url('/static/user.jpg');
		// background-repeat: no-repeat;
		// background-size: cover;
		background: #000;
		position: relative;
		left: 0;
		right: 0;
	}

	.video-flip {
		transform: rotateX(180deg);
	}

	.w6em {
		width: 220rpx !important;
		margin: 0 16rpx;
	}

	.btncon {
		display: flex;
		width: 400rpx;
		margin: 0rpx auto;
		margin-top: 22rpx;
		// background-color: pink;
	}

	.mlr10 {
		margin-left: 9px;
		width: 120rpx !important;
		height: 70rpx;
		margin-top: -1rpx;
	}
}
</style>
